<template>
<div>
  <van-nav-bar
    title="修改头像"
    left-arrow
    @click-left="$router.push('/appPerson')"
     :fixed="true"
  />
  <img ref="image" :src="user.picture" style="max-height: 60vh">
  <input type="file" @change="handleChange" />
  <div>
    <van-button block style="height: 50px;margin-top: 20px" type="primary" @click="cropImage">截取图片</van-button>
    <van-button block style="margin-top: 10px;border-color: white;height: 50px;background-color: #2b85e4;color: white" type="info" @click="$router.push('/appPerson')">返回</van-button>

  </div>
</div>
</template>
<script>
import Vue from 'vue';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
import {NavBar, Toast} from 'vant';
import request from "../../../utils/request";
import { Button } from 'vant';

Vue.use(Button);
Vue.use(NavBar);
export default {
  data(){
    return{
      user:{},
      cropper:null,
    }
  },
  mounted() {
    const image = this.$refs.image;
    this.cropper = new Cropper(image, {
      aspectRatio: 1,
      viewMode: 1,
      dragMode: 'move',
      cropBoxResizable: true,
      toggleDragModeOnDblclick: false
    });
  },
  created() {
    this.user.picture=this.$route.query.pic
  },
  methods:{
    handleChange(event) {
      const file = event.target.files[0];
      const reader = new FileReader();

      reader.onload = (e) => {
        this.user.picture = e.target.result;
        this.cropper.replace(this.user.picture);
      };

      reader.readAsDataURL(file);
    },
    cropImage() {
// 获取裁剪后的图片数据
      const canvas = this.cropper.getCroppedCanvas();

// 获取画布上的图像数据（Base64格式）
      const imageData = canvas.toDataURL('image/jpeg');
      this.user.picture=imageData
      request.post('/user/updateCurrentAvatar',{picture:this.user.picture}).then(resp=>{
        if (resp.code===200){
          this.$router.push('/appPerson')
          Toast(resp.errorMessage)
        }
      })
    },
  }
}
</script>
<style scoped>
/* 这里是示例的基本样式，具体可以按照需求自行修改 */
img {
  max-width: 100%;
}
>>> .van-nav-bar .van-icon{
  color: black;
}
</style>
